package com.bookmall.dao;

import com.bookmall.model.Order;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Squking on 2018/5/16.
 */
public class OrderDAO {
    private static String SQL_InsertOrder = "INSERT INTO orderForm(orderNum, logname, orderContent, sum) VALUES (?, ?, ?, ?)";
    private static String SQL_GetAllOrderByName = "SELECT * FROM orderForm WHERE logname=\'%s\'";

    public void insert(Order order) throws Exception {
        PreparedStatement pstmt = null ;
        DBConnection dbc = null ;
        // 下面是针对数据库的具体操作
        try{
            // 连接数据库
            dbc = new DBConnection() ;
            pstmt = dbc.getConnection().prepareStatement(SQL_InsertOrder) ;
            pstmt.setInt(1, order.getOrderNum());
            pstmt.setString(2, order.getLogname());
            pstmt.setString(3, order.listBook2contentString());
            pstmt.setFloat(4, order.getSum());
            // 进行数据库更新操作
            pstmt.executeUpdate() ;
            pstmt.close() ;
        }catch (Exception e){
            throw new Exception("操作出现异常") ;
        }
        finally{
            // 关闭数据库连接
            dbc.close() ;
        }
    }

    public List<Order> getAllOrders(String logname) throws Exception {
        String sql = String.format(SQL_GetAllOrderByName, logname);
        PreparedStatement pstmt = null ;
        DBConnection dbc = null ;
        // 下面是针对数据库的具体操作
        try{
            // 连接数据库
            dbc = new DBConnection() ;
            pstmt = dbc.getConnection().prepareStatement(sql) ;
            // 进行数据库更新操作
            ResultSet resultSet = pstmt.executeQuery();
            List<Order> listOrder = new ArrayList<>();
            while (resultSet.next())
            {
                int orderNum = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String orderContent = resultSet.getString(3);
                float sum = resultSet.getFloat(4);
                Order order = new Order();
                order.setOrderNum(orderNum);
                order.setLogname(name);
                order.setOrderContent(orderContent);
                order.setSum(sum);
                listOrder.add(order);
            }
            pstmt.close() ;
            return listOrder;
        }catch (Exception e){
            throw new Exception("操作出现异常") ;
        }
        finally{
            // 关闭数据库连接
            dbc.close() ;
        }
    }
}
